package com.cosina.game.crystallight.ui.battle;

import android.graphics.Canvas;
import android.graphics.drawable.BitmapDrawable;
import android.os.SystemClock;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;

import com.cosina.game.crystallight.CrystalLightActivity;
import com.cosina.game.crystallight.engine.BattleEngine;
import com.cosina.game.crystallight.engine.util.FPS;
import com.cosina.game.crystallight.ui.activity.ActivityStatus;
import com.cosina.game.crystallight.ui.battle.layer.BackgroundLayer;
import com.cosina.game.crystallight.ui.monster.MonsterResource;
import com.cosina.game.crystallight.util.DialogUtil;

public class BattleView extends View {

	private final ActivityStatus activityStatus;

	public BattleView(CrystalLightActivity context) {
		super(context);
		this.activityStatus = context.getStatus();
		DrawableManager.init();
		MonsterResource.init();
		this.setBackgroundDrawable(new BitmapDrawable(new BackgroundLayer()
				.getLayer()));
	}

	@Override
	public void onDraw(Canvas canvas) {
		long timeMark = SystemClock.currentThreadTimeMillis();
		drawContent(canvas);

		if (activityStatus.isRunning()) {
			for (int i = 0; i < BattleEngine.speedManager.currentSpeed; i++) {
				BattleEngine.withTimeGoRoot();
			}
		}

		long usedTime = SystemClock.currentThreadTimeMillis() - timeMark;
		{
			Log.d("cosina1985", usedTime + "usedTime");
		}
		this.postInvalidateDelayed(FPS.flushInternal - usedTime);
	}

	private void drawContent(Canvas canvas) {
		DrawableManager.draw(canvas);
	}

	
	@Override
	public boolean onTouchEvent(MotionEvent event) {
		if (event.getAction() == MotionEvent.ACTION_UP) {
			BattleEngine.touchHandler.handler((int) event.getX(), (int) event
					.getY());
		}
		return super.onTouchEvent(event);
	}

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK) {
			doShowQuiteDialog();
			return true;
		}
		return super.onKeyDown(keyCode, event);
	}

	private void doShowQuiteDialog() {
		DialogUtil.show(this.getContext(), "Crystallight", "Exit to Menu?",
				"YES", "NO", goBackRunnable);
	}

	private final Runnable goBackRunnable = new Runnable() {
		@Override
		public void run() {
			((CrystalLightActivity) BattleView.this.getContext()).doShowMap();
		}
	};
}
